package com.briup.xml;

import org.xml.sax.Attributes;
import org.xml.sax.HandlerBase;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * java se 提供的基于sax解析的解析方式
 */
public class SaxParse {
    public static void main(String[] args) {
        //创建工厂实例
        SAXParserFactory factory = SAXParserFactory.newInstance();
        try {
        //工厂创建解析器
            SAXParser saxParser = factory.newSAXParser();
            //解析xml
            saxParser.parse("C:\\Users\\sxx\\IdeaProjects\\bttc-java-basic-code\\02code\\src\\com\\briup\\xml\\file\\class.xml", new DefaultHandler(){
                @Override
                //遇到根元素的开始标签 会调用这个方法
                public void startDocument() throws SAXException {
                    System.out.println("开始解析文档");
                }

                @Override
                public void endDocument() throws SAXException {
                    System.out.println("文档解析结束");
                }

                @Override
                public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                    StringBuilder text=new StringBuilder("\t"+qName);
                    if (!(attributes.getLength() <1)) {
                        text.append(" [");
                        //开始标签上有属性
                        for (int i = 0; i < attributes.getLength(); i++) {
                            String name = attributes.getQName(i);
                            String value = attributes.getValue(i);
                            text.append(name+":"+value+",");
                        }
                        //截取字符串
                      text= new StringBuilder(text.substring(0,text.length()-1));
                        text.append("]");
                    }
                        System.out.println(text);
                }

                @Override
                public void endElement(String uri, String localName, String qName) throws SAXException {
                    System.out.println("\t"+qName);
                }

                @Override
                public void characters(char[] ch, int start, int length) throws SAXException {
                    String s = new String(ch, start, length);
                    String trim = s.trim();
                    if (trim.length()>0) System.out.println("\t\t"+trim);

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
